package MovieGuessingGame.confirmRegistration;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

class RegistrationClientSSL {	
	BufferedWriter bufferedwriter = null;
	SSLSocket sslsocket = null;
	BufferedReader bufferedreader = null;
	String message = null;

	byte[] hashValue = null;
	
	public String getMessage() {
		return message;
	}
	
	void clientConnect (String host) {
		try {
			System.setProperty("javax.net.ssl.trustStore", "C:\\apps_bna\\workspace_ecds\\MovieGuessingGame\\pkeystore.jks");
			SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory
					.getDefault();
			
			sslsocket = (SSLSocket) sslsocketfactory.createSocket(
					host, 30500);

			OutputStream outputstream = sslsocket.getOutputStream();
			OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
			bufferedwriter = new BufferedWriter(outputstreamwriter);

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
	void  clientSend(String userName, String regCode, String password) throws IOException{
		bufferedwriter.write(userName+ "," + regCode + ',' + password + '\n');
		bufferedwriter.flush();
	}
	
	int clientReceive() throws IOException{
		
		InputStream inputstream = sslsocket.getInputStream();
		InputStreamReader inputstreamreader = new InputStreamReader(
				inputstream);
		
		bufferedreader = new BufferedReader(inputstreamreader);

		int intval;
		
		byte[] storage = new byte[32];
		inputstream.read(storage);
		
		for (int i=0; i < 32; i++) {
			//intval = bufferedreader.read();
			//if (intval == -1) break;
			//storage[i] = (byte)(intval);
			
			// System.out.println(storage[i]);
		}
		
		String retValue = new String(storage).trim();
		System.out.println("The return value (RegistrationClientSSL) is: " + retValue);
		
		//byte[] array = response.getBytes();
		//System.out.println(response);
		message = retValue;
		
		System.out.println("The value of retValue is: " + retValue);
		
		if (!retValue.trim().equals("OK"))
		{
			return -1;
		}
		else 
		{
			return 0;
		}
	}
	
	public static void main(String[] arstring) {
		RegistrationClientSSL regClient = new RegistrationClientSSL();
		try {
			regClient.clientConnect("localhost");
			String a = "a";

			regClient.bufferedwriter.write("userName"+ "," + "password" + '\n');
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}
